package com.sdx.console.evaluation.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.evaluation.entity.CpTaskRule;
import com.sdx.console.evaluation.service.CpTaskRuleService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.evaluation.entity.*;
import com.sdx.console.evaluation.service.*;
import com.sdx.console.evaluation.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * CpTaskRule 接口
 */
@RequestMapping("/evaluation/cpTaskRule")
@Controller
public class CpTaskRuleController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(CpTaskRuleController.class);
    private static final String MODEL = "/evaluation/cpTaskRule";


    @Resource
	private CpTaskRuleService cpTaskRuleService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("evaluation.cpTaskRule.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("evaluation.cpTaskRule.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer ruleId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        CpTaskRule cpTaskRule = cpTaskRuleService.queryById(ruleId);
        view.addObject("cpTaskRule", cpTaskRule);
		setPageParam(view,request);
		try {
			view.addObject("cpTaskRuleJson", JacksonUtils.toJsonString(cpTaskRule,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("evaluation.cpTaskRule.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("evaluation.cpTaskRule.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CpTaskRule condtion)
    {
        PageQuery page = condtion.getPageQuery();
        cpTaskRuleService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,CpTaskRule cpTaskRule,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			cpTaskRule.setCreatedBy(user.getId().intValue());
			cpTaskRule.setCreatedName(user.getName());
			cpTaskRule.setCreatedTime(new Date());
			cpTaskRule.setUpdatedBy(user.getId().intValue());
			cpTaskRule.setUpdatedName(user.getName());
			cpTaskRule.setUpdatedTime(new Date());
			cpTaskRuleService.save(cpTaskRule);
		} else {
			cpTaskRule.setUpdatedBy(user.getId().intValue());
			cpTaskRule.setUpdatedName(user.getName());
			cpTaskRule.setUpdatedTime(new Date());
			cpTaskRuleService.updateTemplate(cpTaskRule);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("evaluation.cpTaskRule.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CpTaskRule cpTaskRule,HttpServletRequest request
		)
    {

        return save(true,cpTaskRule,request
		);
    }

    @PostMapping("/update.json")
    @Function("evaluation.cpTaskRule.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  CpTaskRule cpTaskRule,HttpServletRequest request
		) {
		return save(false,cpTaskRule,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("evaluation.cpTaskRule.query")
    @ResponseBody
    public JsonResult<CpTaskRule>queryInfo(Integer ruleId) {
        CpTaskRule cpTaskRule = cpTaskRuleService.queryById( ruleId);
        return  JsonResult.success(cpTaskRule);
    }

    @PostMapping("/delete.json")
    @Function("evaluation.cpTaskRule.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        cpTaskRuleService.batchDelCpTaskRule(idList);
        return JsonResult.success();
    }


    @PostMapping("/save.json")
    @ResponseBody
    public JsonResult saveRule(Integer taskId,String rules,HttpServletRequest request
    )
    {
        JsonResult result = JsonResult.success();
        CoreUser user = getLoginUser(request);
        JSONArray array = JSONArray.parseArray(rules);
        cpTaskRuleService.delRule(taskId);
        for (Object object : array) {
           CpTaskRule cpTaskRule = new CpTaskRule();
            JSONObject json = (JSONObject)object;
            if(StringUtils.isNotBlank(json.getString("ruleName"))){
                cpTaskRule.setTaskId(taskId);
                cpTaskRule.setRuleName(json.getString("ruleName"));
                cpTaskRule.setMaxQuota(json.getIntValue("maxQuota"));
                cpTaskRule.setMaxValue(json.getIntValue("maxValue"));
                cpTaskRule.setMinValue(json.getIntValue("minValue"));
                cpTaskRule.setCreatedBy(user.getId().intValue());
                cpTaskRule.setCreatedName(user.getName());
                cpTaskRule.setCreatedTime(new Date());
                cpTaskRuleService.save(cpTaskRule);
            }
        }
        return result;

    }


}
